#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include "thread.hpp"
#include <memory>
#include <unistd.h>

uint16_t server_port = 0;
std::string server_ip = "";

static void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " port\n" << std::endl;
}

void* udpSend(void* args)
{
    int sock = *(int*)((ThreadData*)args)->args_;

    std::string message;
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while(true)
    {
        std::cerr << "请输入信息: ";//标准错误流,不会重定向到文件中,只会向标准输出打印
        std::getline(std::cin,message);
        if(message == "quit") break;
        //当client首次发送消息给服务器时,OS会自动bind他的IP和port
        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

    }
}

void* udpRecv(void* args)
{
    int sock = *(int*)((ThreadData*)args)->args_;

    char buffer[1024];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sock, buffer, sizeof buffer, 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout  << buffer << std::endl;
        }
    }
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    server_port = atoi(argv[2]);
    server_ip = argv[1];

    std::unique_ptr<Thread> sender(new Thread(1,udpSend,&sock));//发送消息线程
    std::unique_ptr<Thread> recver(new Thread(2,udpRecv,&sock));//接受消息线程
    
    sender->start();
    recver->start();

    sender->join();
    recver->join();

    close(sock);
    //client一般不会显示的bind

    // std::string message;
    // struct sockaddr_in server;
    // memset(&server,0,sizeof(server));
    // server.sin_family = AF_INET;
    // server.sin_port = htons(atoi(argv[2]));
    // server.sin_addr.s_addr = inet_addr(argv[1]);

    // char buffer[1024];
    // while(true)
    // {
    //     std::cout << "请输入信息: ";
    //     std::getline(std::cin,message);
    //     if(message == "quit") break;
    //     //当client首次发送消息给服务器时,OS会自动bind他的IP和port
    //     sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

    //     struct sockaddr_in temp;
    //     socklen_t len = sizeof(temp);
    //     ssize_t s = recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr*)&temp,&len);
    //     if(s > 0)
    //     {
    //         buffer[s] = 0;
    //         std::cout << "server echo# " << buffer << std::endl;
    //     }
    // }
    return 0;
}